﻿using Soft.Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Soft.Service
{

    /// <summary>
    /// job的基类
    /// </summary>
    public abstract class BaseJob : ErrorResponse, IDisposable
    {

        private bool Disposed;


        ~BaseJob()
        {
            try
            {
                this.Dispose();
            }
            catch
            {
            }
        }


        public void Dispose()
        {
            if (!this.Disposed)
            {
                try
                {
                    this.OnDispose();
                }
                catch
                {
                }
                this.Disposed = true;
            }
        }


        protected virtual void OnDispose()
        {
        }


        /// <summary>
        /// 调用方法
        /// </summary>
        /// <typeparam name="T">方法返回值类型</typeparam>
        /// <param name="code">功能识别码</param>
        /// <param name="invokeParameItems">调用的参数列表</param>
        /// <returns></returns>
        protected ResultCarrierData<T> OnCallFunction<T>(FunctionCode code, InvokeParameCollection invokeParameItems = null)
        {
            ResultCarrierData<T> resultCarrierData = new ResultCarrierData<T>();
            CallMethodInstruction callInstruction = new CallMethodInstruction(code.Code, "");
            if (invokeParameItems != null)
            {
                callInstruction.JsonParams = JsonConvertHelper.ToJson(invokeParameItems);
            }
            ExecuteMethodCallInstructionEventHandle executeMethodCallInstruction = this.ExecuteMethodCallInstruction;
            CarrierJson carrierJson = (executeMethodCallInstruction != null) ? executeMethodCallInstruction(callInstruction) : null;
            if (carrierJson.Succeed)
            {
                resultCarrierData.Data = JsonConvertHelper.FormJson<T>(carrierJson.Json);
                resultCarrierData.CallMilliseconds = carrierJson.CallMilliseconds;
                resultCarrierData.TransmittedMilliseconds = carrierJson.TransmittedMilliseconds;
            }
            else
            {
                resultCarrierData.AddError(carrierJson);
            }
            return resultCarrierData;
        }





        internal ExecuteMethodCallInstructionEventHandle ExecuteMethodCallInstruction;
    }
}
